package com.shamar.blog.web.backend;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.shamar.blog.dto.BlogUserExecution;
import com.shamar.blog.entity.BlogUser;
import com.shamar.blog.service.BlogUserService;
import com.shamar.blog.util.CodeUtil;
import com.shamar.blog.util.FileUtil;
import com.shamar.blog.util.HttpServletRequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author fxm 
 * @date 2020-08-02 21:10
 * @desc 后台用户控制器
 */
@Controller
@RequestMapping("/user")
public class UserController {
	Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private BlogUserService blogUserService;

	/**
	 * 用户login处理逻辑函数
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/douserlogin")
	@ResponseBody
	public Map<String,Object> doUserlogin(HttpServletRequest request){
		//定义返回值
		Map<String,Object> modelMap = new HashMap<>();
		if (!CodeUtil.checkVerifyCode(request)) {
			modelMap.put("success", false);
			modelMap.put("errMsg", "验证码输入错误");
			return modelMap;
		}
		ObjectMapper mapper = new ObjectMapper();
		BlogUser blogUser;
		String userStr = HttpServletRequestUtil.getString(request, "BlogUserStr");
		if (Objects.isNull(userStr)) {
			modelMap.put("success", false);
			modelMap.put("errMsg", "参数数据错误,请重试");
			return modelMap;
		}
		//以上接收前端传递过来的信息,下面使用jackson json databind转换为BlogUser实体类
		try {
			blogUser = mapper.readValue(userStr, BlogUser.class);
		}catch (Exception e){
			modelMap.put("success", false);
			modelMap.put("errMsg", e.toString());
			return modelMap;
		}
		if (blogUser != null){
			//若前端传来的BlogUser不为空,和数据库比对是否有该用户
			//获得登录管理员的信息
			BlogUserExecution be = blogUserService.getBlogUserByCondition(blogUser,0,100);
			//若数据库中存在符合条件的记录
			if (Objects.nonNull(be.getBlogUser())) {
				BlogUser currentBlogUser = be.getBlogUser();
				request.getSession().setAttribute("currentBlogUser", currentBlogUser);
				modelMap.put("success", true);
				modelMap.put("currentBlogUser",currentBlogUser);
				return modelMap;
			}
			modelMap.put("success", false);
			modelMap.put("errMsg", "用户名或密码错误");
			return modelMap;
		}
		modelMap.put("success", false);
		modelMap.put("errMsg", "管理员为空");
		return modelMap;
	}

	/**
	 * login页面
	 * @param request
	 * @return
	 */
	@GetMapping(value = "/userlogin")
	@ResponseBody
	public ModelAndView userLogin(HttpServletRequest request){
		//定义返回值
		ModelAndView  model  =  new ModelAndView("backend/user_login");
		return model;
	}

	/**
	 * 用户登出功能
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/douserlogout")
	@ResponseBody
	public Map<String,Object> doUserLogout(HttpServletRequest request){
		//定义返回值
		Map<String,Object> modelMap = new HashMap<>();
		Object currentBlogUserObj = request.getSession().getAttribute("currentBlogUser");
		if (currentBlogUserObj!=null){
			request.getSession().removeAttribute("currentBlogUser");
		}
		try {
			Object newCurrentBlogUser = request.getSession().getAttribute("currentBlogUser");
			modelMap.put("success",Objects.isNull(newCurrentBlogUser));
		}catch (Exception e){
			logger.error("清除缓存失败,错误:{}", e.getMessage());
		}
//        若session中没有数据,则未登录
		return modelMap;
	}
	/**
	 *
	 */
	/**
	 * 管理员个人页面
	 * @param request
	 * @return
	 */
	@GetMapping(value = "/userprofile")
	@ResponseBody
	public ModelAndView userProfile(HttpServletRequest request){
		//定义返回值
		ModelAndView  model  =  new ModelAndView("backend/user_profile");
		//当前登录的用户
		try{
		BlogUser currentBlogUser = (BlogUser) request.getSession().getAttribute("currentBlogUser");
		Integer currentBlogUserId = currentBlogUser.getId();
		//通过session中的用户id查询数据库中最新的数据
		BlogUser newCurrentBlogUser = new BlogUser(currentBlogUserId);
		newCurrentBlogUser = blogUserService.getBlogUserByCondition(newCurrentBlogUser,0,100).getBlogUser();
		model.addObject("blogUser",newCurrentBlogUser);
		return model;
		}
		catch (Exception e){
			return model;
		}
	}

	@PostMapping(value = "/testlogin")
	@ResponseBody
	public Map<String,Object> testLogin(HttpServletRequest request){
		//定义返回值
		Map<String,Object> modelMap = new HashMap<>();
		Object currentBlogUserObj = request.getSession().getAttribute("currentBlogUser");
        //若session中没有数据,则未登录
		if (Objects.isNull(currentBlogUserObj)) {
			modelMap.put("success", false);
			modelMap.put("errMsg", "未登录");
		}
		else{
			BlogUser blogUser = (BlogUser) currentBlogUserObj;
			if (!blogUser.getId().equals(0)) {
				modelMap.put("success",true);
				modelMap.put("errMsg","已登录");
			}
		}
		return modelMap;
	}

	/**
	 * 接收前端传过来的数据,更新数据库中的用户记录
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/updateuser")
	@ResponseBody
	public Map<String,Object> updateUser(HttpServletRequest request){
		//定义返回值
		Map<String,Object> modelMap = new HashMap<>();
		Object currentBlogUserObj = request.getSession().getAttribute("currentBlogUser");
        //若session中没有数据,则未登录
		if (currentBlogUserObj == null){
			modelMap.put("success",false);
			modelMap.put("errMsg","未登录");
		}
		else{
			ObjectMapper mapper = new ObjectMapper();
			BlogUser blogUser;
			String userStr = HttpServletRequestUtil.getString(request, "BlogUserStr");
			if (Objects.isNull(userStr)) {
				modelMap.put("success",false);
				modelMap.put("errMsg","参数传输错误,请重试");
				return modelMap;
			}
			//以上接收前端传递过来的信息,下面使用jackson json databind转换为BlogUser实体类
			try {
				blogUser = mapper.readValue(userStr, BlogUser.class);
				blogUser.setLastEdittime(new Date());
			}catch (Exception e){
				modelMap.put("success", false);
				modelMap.put("errMsg", e.toString());
				return modelMap;
			}
			Integer affectedNum = blogUserService.updateBlogUser(blogUser);
			if (affectedNum > 0){
				modelMap.put("success", true);
			}else {
				modelMap.put("success", false);
				modelMap.put("errMsg", "数据库错误");
			}
		}
		return modelMap;
	}


}
